package com.shopping.controller;

import com.shopping.pojo.*;
import com.shopping.pojo.vo.*;
import com.shopping.service.*;
import com.shopping.utils.R;
import com.shopping.utils.TokenUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

@RestController
@Api(tags = "商家控制类")
public class BusinessController {
    @Autowired
    private BusinessService businessService;
    @Autowired
    private UserService userService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private OrderItemService orderItemService;
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private ProductSpecService productSpecService;
    @Autowired
    private CommentService commentService;

    @ApiOperation("商家登录接口")
    @PostMapping("api/business/login")
    public R login(String businessId, String password) {
        // 判断用户名密码是否正确
        if (businessService.checkBusinessIdAndPassword(businessId, password)) {
            // 生成token
            String token = TokenUtils.token(businessId, "business", businessService.getId(businessId));
            LoginInfo userByToken = TokenUtils.getUserByToken(token);
            Business business = businessService.selectBusiness(businessId);
            if (business.getBusinessStatus() == 0) {
                return R.ok().message("登录成功").data("business", userByToken).data("token", token);
            } else if (business.getBusinessStatus() == 1) {
                return R.error().message("您的店铺正在审核，请耐心等待");
            } else {
                return R.error().message("您的帐号已被加入黑名单，请联系网站工作人员");
            }
        } else {
            return R.error().message("用户名或密码错误");
        }
    }

    @ApiOperation("商家注册接口")
    @PostMapping("api/business/register")
    public R register(Business business, String userName, String name, String phone) {
        // 验证用户信息
        if (userService.checkTransfereeInfo(userName, name, phone)) {
            User user = userService.getUserByUserName(userName);
            // 验证店名唯一
            if (businessService.checkBusinessName(business.getBusinessName())) {
                return R.error().message("店名已被占用");
            } else {
                // 验证店主唯一
                if (businessService.checkBusinessOwner(user.getUserId())) {
                    return R.error().message("您已申请店铺，请误重复申请");
                } else {
                    business.setBusinessOwner(user.getUserId());
                    String str = "DD" + System.currentTimeMillis() + user.getUserId() % 10 + business.getBusinessPhone().charAt(business.getBusinessPhone().length() - 1) + (int) (Math.random() * 90 + 10);
                    business.setBusinessId(str);
                    // 新增店铺
                    if (businessService.insertBusiness(business)) {
                        return R.ok().message("注册申请成功");
                    } else {
                        return R.error().message("注册申请失败");
                    }
                }
            }
        } else {
            return R.error().message("用户信息匹配错误");
        }
    }

    @ApiOperation("商家忘记密码接口")
    @PostMapping("api/business/forget")
    public R forget(String businessId, String name, String businessPhone, String password) {
        // 验证商家信息
        if (businessService.checkBusinessInfo(businessId, name, businessPhone)) {
            // 修改密码
            if (businessService.updateBusinessPass(businessId, password)) {
                return R.ok().message("修改密码成功");
            } else {
                return R.error().message("修改密码失败");
            }
        } else {
            return R.error().message("商家信息匹配错误");
        }
    }

    @ApiOperation("获取商品分类列表接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/selectCategory")
    public R selectCategory() {
        List<String> CategoryList = categoryService.selectCategory();
        return R.ok().message("获取商品分类列表成功~").data("CategoryList", CategoryList);
    }

    @ApiOperation("修改商家头像接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateBusinessImage")
    public R updateBusinessImage(String businessImage, String businessId) {
        if (businessService.updateBusinessImage(businessId, businessImage)) {
            return R.ok().message("上传商家图片成功");
        } else {
            return R.error().message("上传商家图片失败");
        }
    }

    @ApiOperation("上传商家图片接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/onFileChangeBusiness")
    public R onFileChangeBusiness(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error().message("文件上传失败");
        }
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "images" + System.getProperty("file.separator") + "busImg";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeAvatarPath = "/images/busImg/" + fileName;
        try {
            file.transferTo(dest);
            return R.ok().message("上传图片成功").data("businessImage", storeAvatarPath);
        } catch (Exception e) {
            return R.error().message("上传图片失败");
        }
    }

    @ApiOperation("店铺注销接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateBusinessAccount")
    public R updateBusinessAccount(String businessId) {
        // 店铺商品需全部下架
        if (productService.getBusinessProductsNum(businessService.getId(businessId)) > 0) {
            return R.error().message("店铺仍有未下架商品，店铺注销失败");
        } else {
            // 订单需全部完成
            if (orderItemService.checkOrdersStatusByBusinessId(businessId)) {
                return R.error().message("店铺仍有未完结订单，店铺注销失败");
            } else {
                // 注销店铺
                if (businessService.businessCancellation(businessId)) {
                    return R.ok().message("店铺注销成功");
                } else {
                    return R.error().message("店铺注销失败");
                }
            }
        }
    }

    @ApiOperation("店铺转让接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateBusinessTransfer")
    public R updateBusinessTransfer(String businessId, String userName, String name, String phone) {
        // 获取被转让人信息
        User user = userService.getUserByUserName(userName);
        // 店铺商品需全部下架
        if (productService.getBusinessProductsNum(businessService.getId(businessId)) > 0) {
            return R.error().message("店铺仍有未下架商品，转让店铺失败");
        } else {
            // 订单需全部完成
            if (orderItemService.checkOrdersStatusByBusinessId(businessId)) {
                return R.error().message("店铺仍有未完结订单，转让店铺失败");
            } else {
                // 验证信息正确性
                if (userService.checkTransfereeInfo(userName, name, phone)) {
                    // 店铺被转让人不能有店铺
                    if (businessService.checkBusinessOwner(user.getUserId())) {
                        return R.error().message("该用户已有店铺，转让店铺失败");
                    } else {
                        // 转让店铺
                        if (businessService.updateBusinessTransfer(user.getUserId(), businessId)) {
                            return R.ok().message("转让店铺成功");
                        } else {
                            return R.error().message("转让店铺失败");
                        }
                    }
                } else {
                    return R.error().message("该用户信息有误或未注册，转让店铺失败");
                }
            }
        }
    }

    @ApiOperation("修改店铺登录密码接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateBusinessPass")
    public R updateBusinessPass(String businessId, String password, String oldPass) {
        Business business = businessService.selectBusiness(businessId);
        // 验证旧密码
        if (oldPass.equals(business.getPassword())) {
            // 修改密码
            if (businessService.updateBusinessPass(businessId, password)) {
                return R.ok().message("修改店铺登录密码成功");
            } else {
                return R.error().message("修改店铺登录密码失败");
            }
        } else {
            return R.error().message("旧密码错误，修改店铺登录密码失败");
        }
    }

    @ApiOperation("修改店铺信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateBusinessInfo")
    public R updateBusinessInfo(Business business) {
        // 店铺不可重名
        if (business.getBusinessName().equals(businessService.getBusinessName(business.getBusinessId()))) {
            // 店铺更新信息未改店名，店铺信息更新
            if (businessService.updateBusinessInfo(business)) {
                return R.ok().message("修改店铺信息成功");
            } else {
                return R.error().message("修改店铺信息失败");
            }
        } else {
            // 店铺更新信息改店名，验证店铺信息唯一
            if (businessService.checkBusinessName(business.getBusinessName())) {
                // 店铺名验证通过
                if (businessService.updateBusinessInfo(business)) {
                    return R.ok().message("修改店铺信息成功");
                } else {
                    return R.error().message("修改店铺信息失败");
                }
            } else {// 店铺重名
                return R.error().message("店铺名不可重名，修改店铺信息失败");
            }
        }
    }

    @ApiOperation("获取商家信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/selectBusinessInfo")
    public R selectBusinessInfo(String businessId) {
        BusinessInfo businessInfo = businessService.selectBusinessInfo(businessId);
        return R.ok().message("获取商家信息成功~").data("businessInfo", businessInfo);
    }

    @ApiOperation("获取商家产品信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/selectBusinessProductByProductName")
    public R selectBusinessProductByProductName(String businessId, String productName) {
        List<Product> productInfo = productService.selectBusinessProductByProductName(businessId, productName);
        return R.ok().message("获取商家产品信息成功~").data("productInfo", productInfo);
    }

    @ApiOperation("商品上架接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateProductPutOnSale")
    public R updateProductPutOnSale(Integer productId) {
        if (productService.updateProductPutOnSale(productId)) {
            return R.ok().message("商品上架成功");
        } else {
            return R.error().message("商品上架失败");
        }
    }

    @ApiOperation("商品下架接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateProductPullOff")
    public R updateProductPullOff(Integer productId) {
        if (productService.updateProductPullOff(productId)) {
            return R.ok().message("商品下架成功");
        } else {
            return R.error().message("商品下架失败");
        }
    }

    @ApiOperation("新增商品接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/insertProduct")
    public R insertProduct(Product product, String businessId, String cateName) {
        product.setBusinessId(businessService.getId(businessId));
        product.setCateId(categoryService.getCateId(cateName));
        if (productService.insertProduct(product)) {
            return R.ok().message("新增商品成功");
        } else {
            return R.error().message("新增商品失败");
        }
    }

    @ApiOperation("修改商品接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateProduct")
    public R updateProduct(Product product, String cateName) {
        product.setCateId(categoryService.getCateId(cateName));
        if (productService.updateProduct(product)) {
            return R.ok().message("上传商品图片成功");
        } else {
            return R.error().message("上传商品图片失败");
        }

    }

    @ApiOperation("上传商品图片接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/onFileChange")
    public R onFileChange(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return R.error().message("文件上传失败");
        }
        String fileName = System.currentTimeMillis() + file.getOriginalFilename();
        String filePath = System.getProperty("user.dir") + System.getProperty("file.separator") + "images" + System.getProperty("file.separator") + "proImg";
        File file1 = new File(filePath);
        if (!file1.exists()) {
            file1.mkdir();
        }
        File dest = new File(filePath + System.getProperty("file.separator") + fileName);
        String storeAvatarPath = "/images/proImg/" + fileName;
        try {
            file.transferTo(dest);
            return R.ok().message("上传图片成功").data("productImage", storeAvatarPath);
        } catch (Exception e) {
            return R.error().message("上传图片失败");
        }
    }

    @ApiOperation("删除商品接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/deleteProduct")
    public R deleteProduct(Integer productId, String status) {
        // 验证订单状态
        if (orderItemService.checkOrdersStatusByProductId(productId)) {
            return R.error().message("仍有订单未完成，删除商品失败");
        } else {
            // 判断商品状态
            if (status.equals("待上架")) {
                // 待上架直接删除
                if (productService.deleteProduct(productId)) {
                    return R.ok().message("删除商品成功");
                } else {
                    return R.error().message("删除商品失败");
                }
            } else {
                // 修改商品状态隐藏
                if (productService.updateProductDelete(productId)) {
                    return R.ok().message("删除商品成功");
                } else {
                    return R.error().message("删除商品失败");
                }
            }
        }
    }

    @ApiOperation("新增商品规格接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/insertProductSpec")
    public R insertProductSpec(ProductSpec productSpec) {
        if (productSpecService.insertProductSpec(productSpec)) {
            return R.ok().message("新增商品规格成功");
        } else {
            return R.error().message("新增商品规格失败");
        }
    }

    @ApiOperation("修改商品规格接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateProductSpec")
    public R updateProductSpec(ProductSpec productSpec) {
        if (productSpecService.updateProductSpec(productSpec)) {
            return R.ok().message("修改商品规格成功");
        } else {
            return R.error().message("修改商品规格失败");
        }
    }

    @ApiOperation("删除商品规格接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/deleteProductSpec")
    public R deleteProductSpec(Integer id) {
        if (productSpecService.deleteProductSpec(id)) {
            return R.ok().message("删除商品规格成功");
        } else {
            return R.error().message("删除商品规格失败");
        }
    }

    @ApiOperation("获取商家产品信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/selectProductDetailsByProductId")
    public R selectProductDetailsByProductId(Integer productId) {
        ProductInfo productInfo = productService.selectProductInfoByProductId(productId);
        List<ProductSpec> productSpecList = productSpecService.selectProductSpecByProductId(productId);
        List<CommentInfo> commentInfoList = commentService.selectCommentByProductId(productId);
        return R.ok().message("获取商家产品信息成功~").data("productInfo", productInfo).data("productSpecList", productSpecList).data("commentInfoList", commentInfoList);
    }

    @ApiOperation("获取商家订单信息接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/selectOrdersInfoByBusinessId")
    public R selectOrdersInfoByBusinessId(String businessId, String orderId) {
        List<OrdersInfo> ordersInfo = ordersService.selectOrdersInfoByBusinessId(businessId, orderId);
        int totalShipped = orderItemService.getShippedNum(businessId);
        int totalUndelivered = orderItemService.getUndeliveredNum(businessId);
        int totalReceived = orderItemService.getReceivedNum(businessId);
        return R.ok().message("获取商家订单信息成功~").data("ordersInfo", ordersInfo).data("totalUndelivered", totalUndelivered).data("totalShipped", totalShipped).data("totalReceived", totalReceived);
    }

    @ApiOperation("发货接口")
    @ApiImplicitParam(paramType = "header", name = "token", required = true)
    @PostMapping("api/business/updateOrderStatus")
    public R updateOrderStatus(String orderId) {
        if (orderItemService.updateOrderStatus(orderId)) {
            return R.ok().message("发货成功");
        } else {
            return R.error().message("发货失败");
        }
    }

}
